<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="keywords" content="">
  <meta name="description" content="">
  <title>修改用户头像</title>
  <link href="/static/css/bootstrap.min.css" rel="stylesheet"/>
  <link rel="stylesheet" href="/static/include/css/style.css">
  <link href="/static/ajax/libs/cropbox/cropbox.css" rel="stylesheet"/>
  <style type="text/css">

  </style>
</head>
<body class="white-bg">
<div class="container">
  <div class="imageBox">
    <div class="thumbBox"></div>
    <div class="spinner" style="display: none">Loading...</div>
  </div>
  <div class="action">
    <div class="new-contentarea tc">
      <a href="javascript:void(0)" class="upload-img"> <label for="avatar">上传图像</label> </a>
      <form id="formImg" action="" method="post" enctype="multipart/form-data">
        <input type="file" class="" name="file" id="avatar" accept="image/*"/>
      </form>

    </div>
    <input type="button" id="btnCrop" class="Btnsty_peyton" value="裁切"/>
    <input type="button" id="btnZoomIn" class="Btnsty_peyton" value="+"/>
    <input type="button" id="btnZoomOut" class="Btnsty_peyton" value="-"/>
<!--    <input type="hidden" id="avatarUrl" class="Btnsty_peyton"/>-->
  </div>
  <div class="cropped"></div>

</div>
<script src="/static/include/js/footer.js"></script>
<script src="/static/ajax/libs/cropbox/cropbox.js"></script>
<script src="/static/js/jquery.form.min.js"></script>
<script type="text/javascript">
  var cropper;
  var ieImgSrc;
  $(window).load(function () {
    var avatar = JSON.parse(session.get('userInfo')).avatar;
    var options = {
      thumbBox: '.thumbBox',
      spinner: '.spinner',
      imgSrc: $.common.isEmpty(avatar) ? '/static/img/user_w.jpeg' : avatar
    }
    cropper = $('.imageBox').cropbox(options);
    $('#avatar').on('change', function () {
      if (IEVersion()) { //ie8 ie9

        this.select();
        top.parent.document.body.focus();
        ieImgSrc = document.selection.createRange().text;
        $(".thumbBox").html('<div class="ie-img" style="width:100%;height:100%;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=scale,src=\'' + ieImgSrc + '\'"></div>')
        $('.spinner').css('display', 'none')


      } else {
        var reader = new FileReader();
        reader.onload = function (e) {
          options.imgSrc = e.target.result;
          //根据MIME判断上传的文件是不是图片类型
          if ((options.imgSrc).indexOf("image/") == -1) {
            $.modal.alertWarning("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
          } else {
            cropper = $('.imageBox').cropbox(options);
          }
        }
        reader.readAsDataURL(this.files[0]);
      }

    })

    $('#btnCrop').on('click', function () {
      var img = cropper.getDataURL();
      $('.cropped').html('');
      $('.cropped').append('<img src="' + img + '" align="absmiddle" style="width:64px;margin-top:4px;border-radius:64px;box-shadow:0px 0px 12px #7E7E7E;" ><p>64px*64px</p>');
      $('.cropped').append('<img src="' + img + '" align="absmiddle" style="width:128px;margin-top:4px;border-radius:128px;box-shadow:0px 0px 12px #7E7E7E;"><p>128px*128px</p>');
      $('.cropped').append('<img src="' + img + '" align="absmiddle" style="width:180px;margin-top:4px;border-radius:180px;box-shadow:0px 0px 12px #7E7E7E;"><p>180px*180px</p>');
    })

    $('#btnZoomIn').on('click', function () {
      cropper.zoomIn();
    })

    $('#btnZoomOut').on('click', function () {
      cropper.zoomOut();
    })


  });

  function submitHandler() {
    if (IEVersion()){
    // if (true) {
      var img = ieBase64($('#avatar'))
      var ajax_option = {
        url: api + "/admin/sys-file/ieUpload",
        type: "post",
        data: { //ie8ie9不兼容上传文件时添加请求头，所以租户id放在data传给后端
          "TENANT-ID": session.get('tenantId') ? session.get('tenantId') : '',
          "Authorization": 'Bearer ' + session.get('token')
        },
        dataType: "json",
        beforeSubmit: function () {
          $.modal.loading("上传中...");
        },
        success: function (result) {
          $.modal.closeLoading();
          $.modal.msgSuccess(!result.msg ? "上传成功" : result.msg);
          parent.uploadSuccess(result.data.url) //调用父页面函数
          // layer.closeAll("loading");
          $.modal.close()

        },
        error: function (data) {
          layer.alert("上传失败，请重新上传",{icon:2});
        }
      };
      $('#formImg').ajaxSubmit(ajax_option);
      // $.ajaxFileUpload(ajax_option)
    } else {
      var img = cropper.getBlob();
      var formdata = new FormData();
      formdata.append("file", img, getFileName($('#avatar').val()));
      $.ajax({
        url: api + "/admin/sys-file/upload",
        data: formdata,
        type: "post",
        processData: false,
        contentType: false,
        beforeSend: function () {
          $.modal.loading("上传中...");
        },
        success: function (result) {
          $.modal.closeLoading();
          $.modal.msgSuccess(!result.msg ? "上传成功" : result.msg);
          parent.uploadSuccess(result.data.url) //调用父页面函数
          // layer.closeAll("loading");
          $.modal.close()
          // $('#avatarUrl').val(result.data.url)
          // parent.parent.location.reload();
        }
      })
    }
  }

  //获取文件名称
  function getFileName(path) {

    var pos1 = path.lastIndexOf('/');

    var pos2 = path.lastIndexOf('\\');

    var pos = Math.max(pos1, pos2);

    if (pos < 0) return path

    return path.substring(pos + 1);
  }

  //判断ie浏览器版本 以ie10为分界，ie10以下返回true，否则返回false
  function IEVersion() {
    //取得浏览器的userAgent字符串
    var userAgent = navigator.userAgent;
    //判断是否IE浏览器
    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1;
    if (isIE) {
      var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
      reIE.test(userAgent);
      var fIEVersion = parseFloat(RegExp["$1"]);
      if (fIEVersion < 10) {
        return true;
      }
    } else {
      return false;
    }
  }

  function ieBase64(file) {//file是input type="file" 对象dom
    var realPath, xmlHttp, xml_dom, tmpNode, imgData;
    realPath = file;//获取文件的真实本地路径.
    xmlHttp = new ActiveXObject("MSXML2.XMLHTTP");
    xmlHttp.open("POST", realPath, false);
    xmlHttp.send("");
    xml_dom = new ActiveXObject("MSXML2.DOMDocument");
    tmpNode = xml_dom.createElement("tmpNode");
    tmpNode.dataType = "bin.base64";
    tmpNode.nodeTypedValue = xmlHttp.responseBody;
    imgData = "data:image/" + "bmp" + ";base64," + tmpNode.text.replace(/\n/g, "");
    //计算文件大小
    var str = imgData.substring(22);
    var equalIndex = str.indexOf('=');
    if (str.indexOf('=') > 0) {
      str = str.substring(0, equalIndex);
    }
    var strLength = str.length;
    var fileLength = parseInt(strLength - (strLength / 8) * 2);
    if (fileLength > 5120000) {//图片大于5M
      alert("图片不能大于5M");
      return;
    }
    //callback(imgData);
    return imgData;//渲染图片
  }


</script>
</body>
</html>
